﻿namespace LivePatterns
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Reflection;
	using System.Reflection.Emit;

	public static partial class Build
	{
		/// <summary>
		/// Distributes operations across multiple instances.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="objects">Instances to distribute operations.</param>
		/// <returns>Returns a load balancer proxy.</returns>
		/// <remarks>The load balancer uses the Round-robin method to distribute workload. Only method invocations are allowed.</remarks>
		/// <example>
		/// IService s1, s2, s3;
		/// IService loadBalancer = Build.LoadBalance&lt;IService&gt;(s1, s2, s3);
		/// loadBalancer.DoWork(1);
		/// loadBalancer.DoWork(2);
		/// loadBalancer.DoWork(3);
		/// </example>
		public static T LoadBalance<T>(params T[] objects) where T : class
		{
			if (!typeof(T).IsInterface)
				throw new ArgumentException("Only interface types are supported.");

			if (objects == null)
				throw new ArgumentNullException("objects");

			if (!objects.Any())
				throw new ArgumentException("The provided collection contains no elements.", "objects");

			// resolve type from cache, if already built
            if (_loadBalanceTypeCache.ContainsKey(typeof(T)))
                return Activator.CreateInstance(_loadBalanceTypeCache[typeof(T)], objects) as T;

			TypeBuilder typeBuilder = moduleBuilder.DefineType(String.Format("{0}_LoadBalancer_{1}", typeof(T).Name, Guid.NewGuid().ToString().Replace("-", "")), TypeAttributes.Class | TypeAttributes.Public);
			typeBuilder.AddInterfaceImplementation(typeof(T));

			// create a field for storing the object instances
			FieldBuilder fieldBuilder = typeBuilder.DefineField("innerObjects", typeof(T[]), FieldAttributes.Family);
			FieldBuilder counter = typeBuilder.DefineField("index", typeof(int), FieldAttributes.Family);

			// create a construtor, in which we can pass the instances
			ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(T[]) });
			ILGenerator cilg = constructorBuilder.GetILGenerator();
			cilg.ConstructObject();
			cilg.Emit(OpCodes.Ldarg_0);
			cilg.Emit(OpCodes.Ldarg_1);
			cilg.Emit(OpCodes.Stfld, fieldBuilder);
			cilg.Emit(OpCodes.Ldarg_0);
			cilg.Emit(OpCodes.Ldc_I4_0);
			cilg.Emit(OpCodes.Stfld, counter);
			cilg.Emit(OpCodes.Ret);

			// add methods
			MethodBuilder advanceIndexMethod = typeBuilder.DefineMethod("AdvanceIndex", MethodAttributes.Family | MethodAttributes.Virtual);
			ILGenerator aimilg = advanceIndexMethod.GetILGenerator();
			aimilg.Emit(OpCodes.Ldarg_0);
			aimilg.Emit(OpCodes.Ldarg_0);
			aimilg.Emit(OpCodes.Ldfld, counter);
			aimilg.Emit(OpCodes.Ldc_I4_1);
			aimilg.Emit(OpCodes.Add);
			aimilg.Emit(OpCodes.Ldarg_0);
			aimilg.Emit(OpCodes.Ldfld, fieldBuilder);
			aimilg.Emit(OpCodes.Ldlen);
			aimilg.Emit(OpCodes.Rem);
			aimilg.Emit(OpCodes.Stfld, counter);
			aimilg.Emit(OpCodes.Ret);

			MethodBuilder getNextInstanceMethod = typeBuilder.DefineMethod("GetNextInstance", MethodAttributes.Family, typeof(T), null);
			ILGenerator gnimilg = getNextInstanceMethod.GetILGenerator();
			gnimilg.Emit(OpCodes.Ldarg_0);
			gnimilg.Emit(OpCodes.Ldfld, fieldBuilder);
			gnimilg.Emit(OpCodes.Ldarg_0);
			gnimilg.Emit(OpCodes.Ldfld, counter);
			gnimilg.Emit(OpCodes.Ldelem_Ref);
			gnimilg.Emit(OpCodes.Ret);

			// implement fields
			foreach (FieldInfo fi in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance).Where(m => !m.IsSpecialName))
			{
				FieldBuilder fb = typeBuilder.DefineField(fi.Name, fi.FieldType, FieldAttributes.Public | FieldAttributes.Literal);
			}

			// implement properties
			foreach (PropertyInfo pi in typeof(T).GetAllVisibleProperties())
			{
				PropertyBuilder pb = typeBuilder.DefineProperty(pi.Name, PropertyAttributes.None, pi.PropertyType, new Type[0]);
				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				// get method
				if (pi.CanRead)
				{
					MethodInfo getMethod = pi.GetGetMethod();
					methodBuilder = typeBuilder.DefineMethod(
						getMethod.Name, _methodAttributes, getMethod.ReturnType, getMethod.GetParameters().Select(p => p.ParameterType).ToArray()
					);

					ilGenerator = methodBuilder.GetILGenerator();
					ilGenerator.ThrowException(typeof(InvalidOperationException), "Cannot read property values through a load balancer object.");
					pb.SetGetMethod(methodBuilder);
				}

				// set method
				if (pi.CanWrite)
				{
					MethodInfo setMethod = pi.GetSetMethod();
					methodBuilder = typeBuilder.DefineMethod(
						setMethod.Name, _methodAttributes, setMethod.ReturnType, setMethod.GetParameters().Select(p => p.ParameterType).ToArray()
					);

					ilGenerator = methodBuilder.GetILGenerator();
					ilGenerator.ThrowException(typeof(InvalidOperationException), "Cannot change property values through a load balancer object.");
					pb.SetSetMethod(methodBuilder);
				}
			}

			// implement methods
			foreach (MethodInfo mi in typeof(T).GetAllVisibleMethods())
			{
				MethodBuilder methodBuilder = typeBuilder.DefineMethod(
					mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, mi.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ILGenerator ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Call, getNextInstanceMethod);
				ilGenerator.LoadAllArguments(mi);
				ilGenerator.Emit(OpCodes.Callvirt, mi);
				ilGenerator.Emit(OpCodes.Ldarg_0);
				ilGenerator.Emit(OpCodes.Call, advanceIndexMethod);
				ilGenerator.Return();
			}

			// implement events
			foreach (EventInfo ei in typeof(T).GetAllVisibleEvents())
			{
				// define event
				EventBuilder eb = typeBuilder.DefineEvent(ei.Name, EventAttributes.None, ei.EventHandlerType);
				MethodBuilder methodBuilder;
				ILGenerator ilGenerator;

				//
				// implement add method
				//
				MethodInfo addMethod = ei.GetAddMethod();
				methodBuilder = typeBuilder.DefineMethod(
					addMethod.Name, _methodAttributes, addMethod.ReturnType, addMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.ThrowException(typeof(InvalidOperationException), "Cannot subscribe to the events of a load balancer object.");
				eb.SetAddOnMethod(methodBuilder);

				//
				// implement remove method
				//
				MethodInfo removeMethod = ei.GetRemoveMethod();
				methodBuilder = typeBuilder.DefineMethod(
					removeMethod.Name, _methodAttributes, removeMethod.ReturnType, removeMethod.GetParameters().Select(p => p.ParameterType).ToArray()
				);

				ilGenerator = methodBuilder.GetILGenerator();
				ilGenerator.ThrowException(typeof(InvalidOperationException), "Cannot unsubscribe from the events of a load balancer object.");
				eb.SetRemoveOnMethod(methodBuilder);
			}

			return Activator.CreateInstance(typeBuilder.CreateType(), args: new object[] { objects }) as T;
		}

		private static readonly IDictionary<Type, Type> _loadBalanceTypeCache = new Dictionary<Type, Type>();
	}
}